package com.model.dao;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.dto.cart.CartDTO;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.utils.ApplicationUtils;

public class OrderDAO {
	private static final Log log = LogFactory.getLog(OrderDAO.class);

	public String createOrder(List<CartDTO> list) {

		return ApplicationUtils.createTimeStamp();
	}

	Session session;
	Transaction tx;

	public int persist(OrderTable transientInstance) throws Exception {
		log.debug("persisting OrderTable instance");
		int id;
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			session.persist(transientInstance);
			session.flush();
			id=transientInstance.getOrderId();
			tx.commit();
			log.debug("persist successful");
		} catch (Exception ex) {
			
			if (tx != null && tx.isActive()) {
				tx.rollback();
			}
			if(session.isOpen())
				session.close();
			log.error("persist failed", ex);
			throw ex;
		}
		return id;
	}

	/*public static void main(String[] args) {
		OrderDAO dao = new OrderDAO();
		OrderTable table = new OrderTable();
//		table.setOrderId(1);
		table.setDateOfOrder(new Date());
		Set<OrderItemsTable> orderItemsTables = new HashSet<OrderItemsTable>(0);
		for (int i = 0; i < 3; i++) {
			OrderItemsTable orderItemsTable = new OrderItemsTable();
			ChildcatalogTableDAO dao2=new ChildcatalogTableDAO();
			ChildcatalogTable childcatalogTable= dao2.findById(i);
			orderItemsTable.setChildcatalogTable(childcatalogTable);
			orderItemsTable.setOrderTable(table);
			orderItemsTable.setItemQty(i);
			orderItemsTables.add(orderItemsTable);
		}
		table.setOrderItemsTables(orderItemsTables);
		table.setOrderStatus("Submitted");
		table.setPrice("100");
		UserTableDAO dao2 = new UserTableDAO();
		UserTable usertable = dao2.findById(1);
		table.setUserTable(usertable);
		dao.persist(table);
	}*/

	public void remove(OrderTable persistentInstance) throws Exception {
		log.debug("removing OrderTable instance");
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			session.delete(persistentInstance);
			tx.commit();
			log.debug("remove successful");
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("persist failed", ex);
			throw ex;
		}
	}

	public OrderTable merge(OrderTable detachedInstance) throws Exception {
		log.debug("merging OrderTable instance");
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			OrderTable result = (OrderTable) session.merge(detachedInstance);
			tx.commit();
			log.debug("merge successful");
			return result;
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("persist failed", ex);
			throw ex;
		}
	}

	public OrderTable findById(int id) throws Exception {
		log.debug("getting OrderTable instance with id: " + id);
		try {
			session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			tx = session.beginTransaction();
			OrderTable instance = (OrderTable) session
					.get(OrderTable.class, id);
			tx.commit();
			log.debug("get successful");
			return instance;
		} catch (Exception ex) {
			session.close();
			if (tx != null) {
				tx.rollback();
			}
			log.error("persist failed", ex);
			throw ex;
		}
	}
	//change query to get guest details for orders
	@SuppressWarnings("unchecked")
	public List<OrderTable> findAll(){
		log.debug("getting All OrderTable instances ");
		try {
			Session session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			Transaction tx = session.beginTransaction();
			Query query = session.createQuery("select distinct ot from OrderTable ot Join fetch ot.orderItemsTables oit  " +
																					"join fetch oit.childcatalogTable cct " +
																					"join fetch cct.mastercatalogTable " +
																					"left join fetch ot.userTable ut " +
																					"left join fetch ot.guestTable gt " +
					"where orderstatus <> 'Delivered'");
			List<OrderTable> list = query.list();
			tx.commit();
			log.debug("get successful");
			return list;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	@SuppressWarnings("unchecked")
	public List<OrderTable> findMyOrders(int id){
		log.debug("getting All OrderTable instances ");
		try {
			Session session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			Transaction tx = session.beginTransaction();
			Query query = session.createQuery("select distinct ot from OrderTable ot Join fetch ot.orderItemsTables oit  " +
																					"join fetch oit.childcatalogTable cct " +
																					"join fetch cct.mastercatalogTable " +
					"where ot.userTable.iduserTable = "+id+"order by ot.dateOfOrder desc");
			List<OrderTable> list = query.list();
			tx.commit();
			log.debug("get successful");
			return list;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	public List<OrderTable> findOrdersFromDate(Date startDate,Date endDate){
		log.debug("getting All OrderTable instances ");
		try {
			Session session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			Transaction tx = session.beginTransaction();
			Criteria criteria = session.createCriteria(OrderTable.class);
			criteria.add(Restrictions.between("dateOfOrder", startDate, endDate));
			List<OrderTable> list = criteria.list();
			tx.commit();
			log.debug("get successful");
			return list;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public void updateStatus(int id,String status){
		log.debug("updating MastercatalogTable instance ");
		try {
			Session session = SessionFactoryUtil.getSessionFactory()
					.getCurrentSession();
			Transaction tx = session.beginTransaction();
			Query query = session.createQuery("update OrderTable ot "+
					"set orderStatus= '"+status+"' where ot.orderId = "+id);
			query.executeUpdate();
			tx.commit();
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}
	public static void main(String[] args) {
		OrderDAO dao=new OrderDAO();
//		dao.findMyOrders(1);
//		dao.updateStatus(4, "Packed");
//		Calendar calendar=Calendar.getInstance();
//		calendar.set(2013, 9, 17);
//		Calendar calendar2=Calendar.getInstance();
//		calendar2.set(2013, 10, 22);
//		dao.findOrdersFromDate(calendar.getTime(),calendar2.getTime());
		System.out.println(dao.findAll().size());
	}
}
